<?php
namespace csv;

class Csv
{
    //导出csv文件
    public function put_csv($list,$title)
    {
        $file_name = "exam".date('Y-m-d H:s:i', time()).".csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name );
        header('Cache-Control: max-age=0');
        $file = fopen('php://output',"a");
        $limit = 1000;
        $calc = 0;
        foreach ($title as $v){
            $tit[] = iconv('UTF-8', 'GB2312//IGNORE',$v);
        }
        fputcsv($file,$tit);
        foreach ($list as $v){
            $calc++;
            if($limit == $calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($v as $t){
                $tarr[] = iconv('UTF-8', 'GB2312//IGNORE',$t);
            }
            fputcsv($file,$tarr);
            unset($tarr);
        }
        unset($list);
        fclose($file);
        exit();

        // 使用：
        // $csv = new Csv();
        // $list = \think\Db::table('d_accesses')->field('name, sign, pid, sort')->select();
        // $csv_title = array('名称','规则','PID','排序');
        // $csv->put_csv($list, $csv_title);
    }
   
    // csv导入,此格式每次最多可以处理1000条数据  
    public function input_csv($csv_file)
    {  
        $result_arr = array ();  
        $i = 0;  
        while($data_line = fgetcsv($csv_file,10000)) {  
            if ($i == 0) {  
                $GLOBALS ['csv_key_name_arr'] = $data_line;  
                $i ++;  
                continue;  
            }      
            foreach($GLOBALS['csv_key_name_arr'] as $csv_key_num => $csv_key_name ) {  
                //索引下标
                $result_arr[$i][] = iconv('gbk', 'utf-8', $data_line[$csv_key_num]);
                //关联下标
                // $result_arr[$i][iconv('gbk', 'utf-8', $csv_key_name)] = iconv('gbk', 'utf-8', $data_line[$csv_key_num]);
                // $result_arr[$i][$csv_key_name] = iconv('gbk', 'utf-8', $data_line[$csv_key_num]);
            }  
            $i++;  
        }  
        return $result_arr;  

        //使用
        // $csv = new Csv();  //实例化后才可以调用之前类文件定义好的方法
        // $pathname = ROOT_PATH.'public'.DS.'uploads/exam2019-11-21 17_38_04.csv';
        // $handle = fopen($pathname,'r');
        // $list = $csv->input_csv($handle);
        // dump($list);
    }  
}
?>